<!--
  Copyright (c) 2006-2013, JGraph Ltd
  
  JSON data example for mxGraph. This example demonstrates using
  JSON to encode/decode parts of the graph model in mxCodec.
-->
<html>
<head>
    <title>JSON data example for mxGraph</title>
    <link th:href="@{/css/bootstrap.min.css}" href="../static/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link th:href="@{/css/plugins/bootstrap-table/bootstrap-table.min.css}"
          href="../static/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link th:href="@{/css/font-awesome.css}" href="../static/css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link th:href="@{/css/animate.css}" href="../static/css/animate.css" rel="stylesheet">
    <link th:href="@{/css/style.css}" href="../static/css/style.css?v=4.1.0" rel="stylesheet">

    <!-- Sets the basepath for the library if not in same directory -->
    <script type="text/javascript">
        mxBasePath = "../../plugins/Mxgraph";
    </script>
    <!--	<script type="text/javascript">
            mxBasePath = '../static/plugins/Mxgraph/';
        </script>-->

    <!-- Loads and initializes the library -->
    <script th:src="@{/plugins/Mxgraph/js/mxClient.js}" src="../static/plugins/Mxgraph/js/mxClient.js"></script>
    <!-- 全局js -->
    <script th:src="@{/js/jquery.min.js}" src="../static/js/jquery.min.js?v=2.1.4"></script>
    <!-- layer javascript -->
    <script th:src="@{/js/plugins/layer/layer.min.js}" src="../static/js/plugins/layer/layer.min.js"></script>
    <!-- Bootstrap table -->
    <script th:src="@{/js/plugins/bootstrap-table/bootstrap-table.min.js}"
            src="../static/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script th:src="@{/js/plugins/bootstrap-table/bootstrap-table-mobile.min.js}"
            src="../static/js/plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>
    <script th:src="@{/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js}"
            src="../static/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>

    <!-- Example code -->
    <script type="text/javascript">
        var stepData = null;
        // Program starts here. Creates a sample graph in the
        // DOM node with the specified ID. This function is invoked
        // from the onLoad event handler of the document (see below).
        function main(container) {
            // Checks if the browser is supported
            if (!mxClient.isBrowserSupported()) {
                // Displays an error message if the browser is not supported.
                mxUtils.error('Browser is not supported!', 200, false);
            } else {
                // Disables the built-in context menu
                mxEvent.disableContextMenu(container);

                // Creates the graph inside the given container
                var graph = new mxGraph(container);

                // Enables rubberband selection
                new mxRubberband(graph);

                // Gets the default parent for inserting new cells. This
                // is normally the first child of the root (ie. layer 0).
                var parent = graph.getDefaultParent();

                // Adds cells to the model in a single step
                graph.getModel().beginUpdate();
                try {
                    //loadData
                    var data = loadScriptDetail(getQueryVariable("repositoryId"), getQueryVariable("scriptPath"), getQueryVariable("scriptName"));
                    var result = JSON.parse(data.result);
                    var stepList = result.stepList;
                    var hopsList = result.hopsList;
                    var stepsMap = new Map();

                    //单击事件
                    /*graph.addListener(mxEvent.CLICK, function (sender, evt) {
                        var cell = evt.getProperty('cell');
                        if (cell != null) {
                            var overlays = graph.getCellOverlays(cell);
                            if (overlays == null) {
                                // Creates a new overlay with an image and a tooltip
                                var overlay = new mxCellOverlay(
                                    new mxImage('editors/images/overlays/check.png', 16, 16),
                                    'Overlay tooltip');
                                // Installs a handler for clicks on the overlay
                                overlay.addListener(mxEvent.CLICK, function (sender, evt2) {
                                    mxUtils.alert('Overlay clicked');
                                });

                                // Sets the overlay for the cell in the graph
                                graph.addCellOverlay(cell, overlay);
                            } else {
                                graph.removeCellOverlays(cell);
                            }
                        }
                    });*/
                    // 双击事件
                    graph.addListener(mxEvent.DOUBLE_CLICK, function (sender, evt) {
                        var cell = evt.getProperty('cell');
                        if (cell.data.value.stepType == "TableOutput") {
                            layer.open({
                                type: 1,
                                area: ["500px", '510px'],
                                title: "表输出",
                                content: $('#transEdit_tableOutput'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                                success: function (layero, index) {
                                    cell.data.value.stepInterface.truncateTable == true ? $("#truncateTable").attr("checked", "checked") : null;
                                    $("#outputStepName").val(cell.data.value.stepInterface.name);
                                    $("#tableName").val(cell.data.value.stepInterface.tableName);
                                    $("#commitSize").val(cell.data.value.stepInterface.commitSize);
                                    $("#outputDbName").val(cell.data.value.stepInterface.databaseMeta.databaseName);
                                }
                            });
                        } else if (cell.data.value.stepType == "TableInput") {
                            layer.open({
                                type: 1,
                                area: ["510px", '520px'],
                                title: "表输入",
                                content: $('#transEdit_tableInput'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                                success: function (layero, index) {
                                    $("#sql").val(cell.data.value.stepInterface.sql);
                                    $("#stepName").val(cell.data.value.stepName);
                                    $("#dbName").val(cell.data.value.stepInterface.databaseMeta.databaseName);
                                }
                            });
                        }

                        evt.consume();
                    });
                    //设置文字位置
                    var style = "verticalLabelPosition=bottom;verticalAlign=top;";
                    //加载转换步骤
                    for (j = 0; j < stepList.length; j++) {
                        if (stepList[j].stepType == "TableInput") {
                            stepData = graph.insertVertex(parent, null, stepList[j].stepName, stepList[j].locationX, stepList[j].locationY, 42, 42, `shape=image;image=/img/component/tableInput.svg;` + style);
                        } else if (stepList[j].stepType == "TableOutput") {
                            stepData = graph.insertVertex(parent, null, stepList[j].stepName, stepList[j].locationX, stepList[j].locationY, 42, 42, `shape=image;image=/img/component/tableOutput.svg;` + style);
                        }

                        stepData.data = new CustomData(stepList[j]);
                        stepsMap.set(stepList[j].stepId, stepData);
                    }
                    //加载步骤连接线，后续处理开启，未开启线段编辑
                    for (j = 0; j < hopsList.length; j++) {
                        //var style = [];
                        var from = stepsMap.get(hopsList[j].fromId);
                        var to = stepsMap.get(hopsList[j].toId);
                        var style = "";
                        if (hopsList[j].enabled) {
                            style = 'style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#3d6480;"';
                        } else {
                            style = 'style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;strokeColor=#CCCCCC;"';
                        }
                        graph.insertEdge(parent, null, '', from, to, style);
                    }
                } finally {
                    // Updates the display
                    graph.getModel().endUpdate();
                }
            }

        }
        ;

        function CustomData(value) {
            this.value = value;
        }

        var codec = new mxObjectCodec(new CustomData());

        codec.encode = function (enc, obj) {
            var node = enc.document.createElement('CustomData');
            mxUtils.setTextContent(node, JSON.stringify(obj));

            return node;
        };

        codec.decode = function (dec, node, into) {
            var obj = JSON.parse(mxUtils.getTextContent(node));
            obj.constructor = CustomData;

            return obj;
        };

        mxCodecRegistry.register(codec);

        /**
         * 加载数据
         *
         * @param repositoryId  资源库ID
         * @param scriptPath    脚本路径
         * @param scriptName    脚本名称
         * @returns {null}
         */
        function loadScriptDetail(repositoryId, scriptPath, scriptName) {
            var stepNam = "表输入";
            var resultData = null;
            $.ajax({
                type: 'GET',
                async: false,
                url: '/sys/repository/getScriptByRepository.do?id=' + repositoryId + "&scriptPath=" + scriptPath + "&scriptName=" + scriptName + "&type=trans",
                //url: '/sys/trans/previewData.do?transRepositoryId=' + repositoryId + "&scriptPath=" + scriptPath + "&scriptName=" + scriptName + "&rowLimit=100&stepName=" + stepNam + "&type=trans",
                data: {},
                success: function (data) {
                    resultData = data;
                },
                error: function () {
                    alert("请求失败！请刷新页面重试");
                },
                dataType: 'json'
            });
            return resultData;
        }

        /**
         * 获取URL参数
         *
         * @param variable 变量名
         * @returns {string|boolean}
         */
        function getQueryVariable(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) {
                    return pair[1];
                }
            }
            return (false);
        }

        /**
         * 数据组装
         * 根据脚本的返回值，拼装成mxGraph格式
         *
         * @param graph
         */
        function dataAssembly(graph, data) {

        }

        /**
         *预览SQL，动态table
         */
        function previewSQL() {
            var transRepositoryId = getQueryVariable("repositoryId");
            var scriptPath = getQueryVariable("scriptPath");
            var scriptName = getQueryVariable("scriptName");
            var stepName = $("#stepName").val();
            var previewUrl = '/sys/trans/previewData.do?transRepositoryId=' + transRepositoryId + '&scriptPath=' + scriptPath + '&scriptName=' + scriptName + '&rowLimit=100&stepName=' + stepName;
            $("#previewTable").bootstrapTable({
                ajax: function (request) {
                    $.ajax({
                        type: "GET",
                        url: previewUrl,
                        contentType: "application/json;charset=utf-8",
                        dataType: "json",
                        json: 'callback',
                        success: function (json) {
                            var columnsArray = [];
                            columnsArray.push({field: "state", checkbox: true});
                            for (var i = 0; i < (json.result.columns).length; i++) {//Object.keys(obj) 获取key名称
                                columnsArray.push({
                                    "title": json.result.columns[i].dataIndex,
                                    "field": json.result.columns[i].dataIndex,
                                    switchable: true,
                                    sortable: true
                                });
                            }
                            $('#previewTable').bootstrapTable('destroy').bootstrapTable({
                                data: json.result.firstRecords,
                                singleSelect: true,
                                clickToSelect: true,
                                //sortName: "create_time",
                                //sortOrder: "desc",
                                pageSize: 15,
                                pageNumber: 1,
                                pageList: "[10, 25, 50, 100, All]",
                                showToggle: true,
                                showRefresh: true,
                                showColumns: true,
                                search: true,
                                pagination: true,
                                columns: columnsArray
                            });
                            layer.open({
                                type: 1,
                                area: ['80%', '60%'],
                                title: "表输入",
                                content: $('#previewTable')
                            });
                        },
                        error: function () {
                            alert("错误");
                        }
                    });
                }
            });
        }


    </script>

</head>

<!-- Page passes the container for the graph to the program -->
<body onload="main(document.getElementById('graphContainer'))">

<!-- Creates a container for the graph with a grid wallpaper -->
<div id="graphContainer"
     style="position:relative;overflow:hidden;width:100%;height:100%;background:url('../../plugins/Mxgraph/images/blank.gif');cursor:default;">

</div>

<!-- 表输入 -->
<form class="form-horizontal center-block" role="form">
    <div class="form-group" style="display: none;padding: 5px 5px; " id="transEdit_tableInput">
        <label style="margin-top:10px;" class="col-sm-3 control-label">步骤名称:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <input type="text" class="form-control" id="stepName" name="stepName"
                   placeholder="步骤名称" readonly>
        </div>
        <label style="margin-top:10px;" class="col-sm-3 control-label">数据库连接:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <input type="text" class="form-control" id="dbName" name="dbName"
                   placeholder="数据库连接" readonly>
        </div>
        <label style="margin-top:10px;" class="col-sm-3 control-label">SQL:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <textarea class="form-control" id="sql" name="sql" rows="15" readonly></textarea>
        </div>
        <button type="button" class="btn btn-primary" onclick="previewSQL()">预览</button>
    </div>
</form>

<!-- 表输出 -->
<form class="form-horizontal center-block" role="form">
    <div class="form-group" style="display: none;padding: 5px 5px; " id="transEdit_tableOutput">
        <label style="margin-top:10px;" class="col-sm-3 control-label">步骤名称:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <input type="text" class="form-control" id="outputStepName" name="outputStepName"
                   placeholder="步骤名称" readonly>
        </div>
        <label style="margin-top:10px;" class="col-sm-3 control-label">数据库连接:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <input type="text" class="form-control" id="outputDbName" name="outputDbName"
                   placeholder="数据库连接" readonly>
        </div>
        <label style="margin-top:10px;" class="col-sm-3 control-label">目标表:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <input type="text" class="form-control" id="tableName" name="tableName"
                   placeholder="目标表" readonly>
        </div>
        <label style="margin-top:10px;" class="col-sm-3 control-label">提交记录数量:</label>
        <div style="margin-top:10px;" class="col-sm-9">
            <input type="text" class="form-control" id="commitSize" name="commitSize"
                   placeholder="提交记录数量" readonly>
        </div>
        <label style="margin-top:10px;" class="col-sm-3 control-label">裁剪表:</label>
        <div style="margin-top:16px;" class="col-sm-9">
            <label class="checkbox-inline">
                <input type="checkbox" name="truncateTable" id="truncateTable" value="false" readonly/>
            </label>
        </div>
    </div>
</form>

<!-- 预览数据 动态表格-->
<div>
    <table id="previewTable" class="table table-responsive table-striped
    table-bordered table-hover table-condensed ">
    </table>
</div>
</body>
</html>
